<template>
  <div class="profile-container">
    <div class="page-breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>个人中心</el-breadcrumb-item>
        <el-breadcrumb-item>个人资料</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <el-card class="profile-header" shadow="hover">
      <div class="header-content">
        <div class="avatar-container">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload"
          >
            <div class="avatar-wrapper">
              <el-avatar v-if="userStore.userInfo?.avatar && userStore.userInfo?.avatar !== ''" :size="100" :src="processAvatarUrl(userStore.userInfo?.avatar)" class="user-avatar" />
              <el-avatar v-else :size="100" class="user-avatar">
                {{ userInfo.username?.charAt(0)?.toUpperCase() || 'U' }}
              </el-avatar>
              <div class="avatar-mask">
                <el-icon><Upload /></el-icon>
                <span>更换头像</span>
              </div>
            </div>
          </el-upload>
        </div>
        <div class="user-info">
          <h2>{{ userInfo.nickName || userInfo.username || '用户' }}</h2>
          <p class="user-role">
            <el-tag size="small" type="primary" effect="light" v-for="role in userInfo.roles" :key="role">
              用户名 ： {{ userInfo.username}}
            </el-tag>
          </p>
          <p class="user-meta">
            <span><el-icon><User /></el-icon> ID: {{ userInfo.id || 'N/A' }}</span>
            <span><el-icon><Message /></el-icon> {{ userInfo.email || '未设置邮箱' }}</span>
          </p>
        </div>
      </div>
    </el-card>

    <div class="profile-content">
      <el-tabs v-model="activeTab" class="profile-tabs">
        <el-tab-pane label="基本信息" name="basic">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <h3>基本信息</h3>
                <el-button type="primary" @click="startEdit" v-if="!isEditing">编辑</el-button>
                <div v-else>
                  <el-button @click="cancelEdit">取消</el-button>
                  <el-button type="primary" @click="saveUserInfo" :loading="saveLoading">保存</el-button>
                </div>
              </div>
            </template>
            <el-form
              ref="profileForm"
              :model="editingUserInfo"
              :disabled="!isEditing"
              label-position="right"
              label-width="100px"
              :rules="formRules"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="editingUserInfo.username" placeholder="请输入用户名" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="editingUserInfo.nickName" placeholder="请输入昵称" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editingUserInfo.email" placeholder="请输入邮箱" />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="个人简介" prop="description">
                <el-input
                  v-model="editingUserInfo.description"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入个人简介"
                />
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
      </el-tabs>

    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { User, Message, Upload } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'UserProfile',
  components: {
    User,
    Message,
    Upload
  },
  setup() {
    const userStore = useUserStore()
    const activeTab = ref('basic')
    const isEditing = ref(false)
    const saveLoading = ref(false)
    const profileForm = ref(null)
    
    // 用户基本信息
    const userInfo = computed(() => {
      return {
        id: userStore.userInfo?.id || '',
        username: userStore.username || '',
        nickName: userStore.userInfo?.nickName || '',
        email: userStore.userInfo?.email || '',
        avatar: userStore.avatar || '',
        description: userStore.userInfo?.description || '',
        roles: userStore.roles || []
      }
    })
    
    // 编辑表单数据
    const editingUserInfo = ref({ ...userInfo.value })
    
    // 头像URL处理函数 - 解决Gitee图床CORS问题
    const processAvatarUrl = (url) => {
      if (!url) return url
      // 只要是http开头的都走代理，兼容gitee、oss等
      if (url.startsWith('http')) {
        return `https://images.weserv.nl/?url=${encodeURIComponent(url.replace(/^https?:\/\//, ''))}`
      }
      return url
    }
    
    // 表单验证规则
    const formRules = reactive({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入有效的邮箱地址', trigger: 'blur' }
      ]
    })
    
    // 开始编辑
    const startEdit = () => {
      // 确保使用最新的用户信息
      editingUserInfo.value = { ...userInfo.value }
      isEditing.value = true
    }

    // 刷新用户信息
    const refreshUserInfo = async () => {
      try {
        const { authApi } = await import('@/api/auth')
        const response = await authApi.getUserInfo()
        if (response.isSuccess && response.data) {
          userStore.updateUserInfo(response.data)
          editingUserInfo.value = { ...userInfo.value }
        }
      } catch (error) {
        console.error('刷新用户信息失败:', error)
      }
    }
    
    // 取消编辑
    const cancelEdit = () => {
      isEditing.value = false
      ElMessage.info('已取消编辑')
    }
    
    // 保存用户信息
    const saveUserInfo = async () => {
      if (!profileForm.value) return
      
      try {
        await profileForm.value.validate()
        
        saveLoading.value = true
        
        // 调用API更新用户资料
        const updateData = {
          nickName: editingUserInfo.value.nickName,
          email: editingUserInfo.value.email,
          description: editingUserInfo.value.description
        }
        
        const { authApi } = await import('@/api/auth')
        const response = await authApi.updateProfile(updateData)
        
        if (response.isSuccess) {
          // 更新本地存储
          userStore.updateUserInfo(response.data)
          ElMessage.success('个人信息更新成功')
          isEditing.value = false
        } else {
          ElMessage.error(response.message || '更新失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      } finally {
        saveLoading.value = false
      }
    }
    
    // 头像上传前的验证
    const beforeAvatarUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJpgOrPng) {
        ElMessage.error('头像只能是 JPG 或 PNG 格式!')
        return false
      }
      
      if (!isLt2M) {
        ElMessage.error('头像大小不能超过 2MB!')
        return false
      }
      
      return true
    }
    
    // 处理头像上传
    const handleAvatarUpload = async (options) => {
      const { file } = options
      
      try {
        const { authApi } = await import('@/api/auth')
        const response = await authApi.uploadAvatar(file)
        
        if (response.isSuccess) {
          // 更新用户头像
          userStore.updateAvatar(response.data)
          ElMessage.success('头像上传成功')
        } else {
          ElMessage.error(response.message || '头像上传失败')
        }
      } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('头像上传失败')
      }
    }
    
    // 修改密码相关
    const passwordDialogVisible = ref(false)
    const changePasswordLoading = ref(false)
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    const passwordRules = reactive({
      oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    })

    const showChangePasswordDialog = () => {
      passwordDialogVisible.value = true
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    }

    const changePassword = async () => {
      // 前端校验
      if (!passwordForm.oldPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
        ElMessage.error('请填写完整信息')
        return
      }
      if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        ElMessage.error('两次输入的新密码不一致')
        return
      }
      try {
        changePasswordLoading.value = true
        const { authApi } = await import('@/api/auth')
        const response = await authApi.changePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        if (response.isSuccess) {
          ElMessage.success('密码修改成功')
          passwordDialogVisible.value = false
        } else {
          ElMessage.error(response.message || '密码修改失败')
        }
      } catch (error) {
        ElMessage.error('密码修改失败')
      } finally {
        changePasswordLoading.value = false
      }
    }
    
    onMounted(() => {
      // 可以在这里加载额外的用户信息
      
      // 添加页面加载动画效果
      const profileElements = document.querySelectorAll('.profile-header, .profile-content');
      profileElements.forEach((el, index) => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(20px)';
        el.style.transition = 'all 0.5s ease';
        
        setTimeout(() => {
          el.style.opacity = '1';
          el.style.transform = 'translateY(0)';
        }, 100 * (index + 1));
      });
    })
    
    // 组件挂载时刷新用户信息
    onMounted(() => {
      refreshUserInfo()
    })
    
    return {
      // 用户状态管理
      userStore,
      
      activeTab,
      userInfo,
      editingUserInfo,
      isEditing,
      saveLoading,
      profileForm,
      formRules,
      processAvatarUrl,
      startEdit,
      cancelEdit,
      saveUserInfo,
      refreshUserInfo,
      beforeAvatarUpload,
      handleAvatarUpload,
      passwordDialogVisible,
      passwordForm,
      passwordRules,
      changePasswordLoading,
      showChangePasswordDialog,
      changePassword
    }
  }
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  
  .page-breadcrumb {
    margin-bottom: 20px;
    padding: 8px 0;
    
    :deep(.el-breadcrumb__item) {
      .el-breadcrumb__inner {
        font-weight: 500;
        color: #606266;
        
        &.is-link {
          color: #409eff;
          font-weight: 500;
          
          &:hover {
            color: #66b1ff;
          }
        }
      }
    }
  }
  
  .profile-header {
    margin-bottom: 24px;
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
    overflow: hidden;
    transition: all 0.3s;
    border: none;
    
    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.08);
    }
    
    .header-content {
      display: flex;
      align-items: center;
      padding: 32px;
      background: linear-gradient(45deg, #f1f7fe, #e6f0fd);
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 3px;
        background: linear-gradient(to right, #409eff, #67c23a);
      }
      
      .avatar-container {
        margin-right: 36px;
        
        .avatar-wrapper {
          position: relative;
          display: inline-block;
          cursor: pointer;
          overflow: hidden;
          border-radius: 50%;
          border: 5px solid #fff;
          box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
          transition: all 0.3s;
          
          &:hover {
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
            transform: translateY(-3px);
          }
          
          .user-avatar {
            width: 110px;
            height: 110px;
            background-color: #ecf5ff;
            font-size: 28px;
            font-weight: 600;
            color: #409eff;
            transition: all 0.3s;
          }
          
          .avatar-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: linear-gradient(to bottom, rgba(64, 158, 255, 0.7), rgba(0, 0, 0, 0.5));
            color: white;
            opacity: 0;
            transition: all 0.3s;
            border-radius: 50%;
            backdrop-filter: blur(3px);
            
            .el-icon {
              font-size: 28px;
              margin-bottom: 8px;
              transform: translateY(15px);
              opacity: 0;
              transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            }
            
            span {
              font-size: 15px;
              font-weight: 500;
              letter-spacing: 0.5px;
              transform: translateY(15px);
              opacity: 0;
              transition: all 0.4s 0.1s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            }
          }
          
          &:hover {
            .avatar-mask {
              opacity: 1;
              
              .el-icon, span {
                transform: translateY(0);
                opacity: 1;
              }
            }
            
            .user-avatar {
              filter: blur(2px);
              transform: scale(1.05);
            }
          }
        }
      }
      
      .user-info {
        flex: 1;
        
        h2 {
          margin: 0 0 16px 0;
          font-size: 28px;
          font-weight: 700;
          background: linear-gradient(135deg, #409eff, #67c23a);
          -webkit-background-clip: text;
          background-clip: text;
          -webkit-text-fill-color: transparent;
          display: inline-block;
          position: relative;
          padding-bottom: 8px;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 40px;
            height: 3px;
            background: linear-gradient(135deg, #409eff, #67c23a);
            border-radius: 3px;
          }
        }
        
        .user-role {
          margin-bottom: 16px;
          
          .el-tag {
            margin-right: 8px;
            border-radius: 20px;
            padding: 0 12px;
            height: 28px;
            line-height: 26px;
            border: none;
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
            font-weight: 500;
          }
        }
        
        .user-meta {
          display: flex;
          flex-wrap: wrap;
          gap: 12px;
          
          span {
            display: flex;
            align-items: center;
            background-color: #f0f7ff;
            padding: 8px 16px;
            border-radius: 24px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            transition: all 0.3s;
            color: #555;
            font-weight: 500;
            font-size: 14px;
            
            &:hover {
              background-color: #e0f0ff;
              transform: translateY(-2px);
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            }
            
            .el-icon {
              margin-right: 8px;
              color: #409eff;
              font-size: 16px;
            }
          }
        }
      }
    }
  }
  
  .profile-content {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.07);
    animation: fadeIn 0.5s ease-out;
    
    .profile-tabs {
      padding: 24px;
      
      :deep(.el-tabs__header) {
        margin-bottom: 24px;
        
        .el-tabs__item {
          font-size: 16px;
          padding: 0 20px;
          height: 40px;
          line-height: 40px;
          
          &.is-active {
            font-weight: 600;
          }
          
          &:hover {
            color: var(--el-color-primary-light-3);
          }
        }
        
        .el-tabs__active-bar {
          height: 3px;
          border-radius: 3px;
        }
      }
      
      :deep(.el-tab-pane) {
        animation: fadeIn 0.5s ease-out;
      }
      
      :deep(.el-card) {
        border-radius: 8px;
        transition: all 0.3s;
        overflow: hidden;
        margin-bottom: 20px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        
        &:hover {
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
        }
      }
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 16px;
        margin-bottom: 20px;
        border-bottom: 1px solid #ebeef5;
        
        h3 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: #303133;
          position: relative;
          
          &::before {
            content: '';
            position: absolute;
            left: -12px;
            top: 50%;
            transform: translateY(-50%);
            height: 18px;
            width: 4px;
            background-color: var(--el-color-primary);
            border-radius: 2px;
          }
        }
      }
    }
  }
  
  .security-items,
  .notification-items {
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    .security-item,
    .notification-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 18px 20px;
      background-color: #f8f9fa;
      border-radius: 8px;
      transition: all 0.3s ease;
      border: 1px solid #ebeef5;
      
      &:hover {
        background-color: #f2f6fc;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      }
      
      .security-info,
      .notification-info {
        h4 {
          margin: 0 0 8px 0;
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          display: flex;
          align-items: center;
          
          &:before {
            content: '';
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: var(--el-color-primary);
            margin-right: 8px;
          }
        }
        
        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
          padding-left: 16px;
        }
      }
      
      .el-button {
        transition: all 0.3s;
        border-radius: 6px;
        
        &:hover {
          transform: scale(1.05);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        &.el-button--primary {
          background: linear-gradient(135deg, #409eff, #57a8ff);
          border: none;
          
          &:hover {
            background: linear-gradient(135deg, #57a8ff, #409eff);
          }
          
          &:active {
            animation: pulseButton 0.3s;
          }
        }
      }
    }
  }
  
  .form-action {
    margin-top: 30px;
    text-align: right;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    
    .el-button {
      padding: 12px 24px;
      transition: all 0.3s;
      border-radius: 6px;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      &.el-button--primary {
        background: linear-gradient(135deg, #409eff, #57a8ff);
        border: none;
        
        &:hover {
          background: linear-gradient(135deg, #57a8ff, #409eff);
        }
        
        &:active {
          animation: pulseButton 0.3s;
        }
      }
    }
  }
  
  // 添加微动画
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
  }
  
  @keyframes pulseButton {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
  }
  
  // 表单样式美化
  :deep(.el-form) {
    .el-form-item {
      margin-bottom: 24px;
      
      &.is-error .el-input__wrapper {
        box-shadow: 0 0 0 1px #f56c6c inset;
      }
    }
    
    .el-input__wrapper, 
    .el-textarea__inner {
      box-shadow: 0 0 0 1px #e0e0e0 inset;
      padding: 2px 16px;
      transition: all 0.3s;
      border-radius: 8px;
      background-color: #fcfcfe;
      
      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
        background-color: #fff;
      }
      
      &.is-focus {
        box-shadow: 0 0 0 1px var(--el-color-primary) inset, 0 3px 8px rgba(64, 158, 255, 0.08);
        background-color: #fff;
      }
    }
    
    .el-input {
      --el-input-height: 42px;
      
      .el-input__inner {
        font-size: 15px;
      }
    }
    
    .el-textarea__inner {
      padding: 10px 16px;
      font-size: 15px;
      
      &:focus {
        box-shadow: 0 0 0 1px var(--el-color-primary) inset, 0 3px 8px rgba(64, 158, 255, 0.08);
      }
    }
    
    .el-form-item__label {
      font-weight: 500;
      font-size: 15px;
      color: #333;
    }
    
    .el-select {
      width: 100%;
      
      .el-input {
        width: 100%;
      }
    }
    
    .el-date-editor {
      width: 100%;
    }
  }
  
  // 对话框样式美化
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
    
    .el-dialog__header {
      margin: 0;
      padding: 20px;
      border-bottom: 1px solid #ebeef5;
      background-color: #f8f9fa;
      
      .el-dialog__title {
        font-weight: 600;
      }
    }
    
    .el-dialog__body {
      padding: 24px;
    }
    
    .el-dialog__footer {
      border-top: 1px solid #ebeef5;
      padding: 15px 20px;
    }
  }
}
</style>
